import axios from 'axios';

import { server_base_url, wss_url } from '../config';
import { info } from './common';

export const market = {
    /**
     * 获取市场状态接口
     */
    async getMarketStatus() {
        try {
            const response = await axios.post(`${ server_base_url }/market/time`, {}, {
                headers: { 'Content-Type': 'application/json' }
            });
            const data = response.data;
            info('[ resposeData ] getMarketStatus', data);
            return { success: true, data };
        } catch (err) {
            info('[ err ] getMarketStatus', err);
            return { success: false, err };
        }
    },
    /**
     * 获取市场列表接口
     */
    async getMarketList() {
        try {
            const response = await axios.post(`${ server_base_url }/market/list`, {}, {
                headers: { 'Content-Type': 'application/json' }
            });
            const data = response.data;
            info('[ resposeData ] getMarketList', data);
            return { success: true, data };
        } catch (err) {
            info('[ err ] getMarketList', err);
            return { success: false, err };
        }
    },
    /**
     * 获取历史k线接口
     */
    getHistoryKLineData(symbol, time) {
        let ws = null;
        let kline_data = [];
        try {
            ws = new WebSocket(wss_url);
            return new Promise((resolve, reject) => {
                ws.onopen = (event) => {
                    console.log('连接已建立', this, ws);
                    // 取消订阅最新k线 - 后续操作写在事件监听里
                    sendMessage(ws, JSON.stringify({ id: 5, method: 'kline.unsubscribe', params: [] }));
                };
                // WebSocket 接收消息的监听
                ws.onmessage = (event) => {
                    let data = JSON.parse(event.data);
                    console.log('server 收到消息', data);
                    // 处理取消订阅最新k线的结果
                    if (data.id == 5 && data.result == 'success') {
                        // 查询历史k线
                        sendMessage(ws, JSON.stringify({ id: 6, method: 'kline.query', params: [ symbol, `${ time / 1000 }` ] }));
                    } else if (data.id == 6) {
                        let new_kline_data = [];
                        for (let i = 0; i < data.result.length; i++) {
                            let item = data.result[i];
                            new_kline_data.push({
                                timestamp: item[0] * 1000,
                                open: item[1],
                                close: item[2],
                                high: item[3],
                                low: item[4],
                                volume: item[5]
                            });
                        }
                        console.log('一共返回了 ' + new_kline_data.length + ' 条数据');
                        console.log(new_kline_data);
                        kline_data.unshift(...new_kline_data);
                        console.log('更新后的 kline_data', kline_data);
                        // 限制k线数量为 900 条数据
                        if (data.result.length >= 300 && kline_data.length < 900) {
                            sendMessage(ws, JSON.stringify({ id: 6, method: 'kline.query', params: [ symbol, `${ time / 1000 }`, String(data.result[0][0]) ] }));
                        } else {
                            console.log('数据已全部获取');
                            resolve({ success: true, data: kline_data });
                        }
                    }
                };
                // WebSocket 错误事件的监听
                ws.onerror = (event) => {
                    console.error(`发生错误: ${ event }`);
                    info('[ err ] getHistoryKLineData', event);
                    reject({ success: false, err });
                };
            });
        } catch (err) {
            info('[ err ] getHistoryKLineData', err);
            return { success: false, err };
        }
    },
};

// 发送消息
function sendMessage(ws, s) {
    if (!ws || ws.readyState !== WebSocket.OPEN) {
        console.error('未建立连接或连接未就绪');
        return;
    }

    if (!s) {
        console.error('消息内容不能为空');
        return;
    }

    try {
        ws.send(s);
        console.log(`已发送: ${ s }`);
    } catch (error) {
        console.error(`发送失败: ${ error.message }`);
    }
}